package com.sunchangming.stmdb;

import java.util.ArrayList;

/**
 * 这个类的public方法都是线程安全的。
 * 
 * @author cm
 * 
 */
public class ModuleManager {
	private final ArrayList<Module> modules = new ArrayList<Module>();

	private static volatile ModuleManager instance;

	public static class Param {
		final String name;
		final String classname;

		public Param(String name, String classname) {
			super();
			this.name = name;
			this.classname = classname;
		}

	}

	private static java.util.ArrayList<Param> getModules() {
		final java.util.ArrayList<Param> ret = new java.util.ArrayList<Param>();
		ret.add(new Param("mbean", "com.sunchangming.stmdb.MyMbeanServer"));
		ret.add(new Param("LockManager", "com.sunchangming.stmdb.LockManager"));
		ret.add(new Param("DeadlockDetector", "com.sunchangming.stmdb.DeadlockDetector"));
		ret.add(new Param("DeadlockDetector", "com.sunchangming.stmdb.DebugModule"));
		return ret;
	}

	public static ModuleManager getInstance() {
		if (instance == null) {
			synchronized (ModuleManager.class) {
				if (instance == null)
					instance = new ModuleManager();
			}
		}
		return instance;
	}

	/**
	 * 
	 * @param modules
	 *            null代表初始化所有模块。否则为初始化特定模块，这里面放的是模块名
	 * @throws Exception
	 */
	synchronized public void init(java.util.Collection<String> modules) throws Exception {
		final java.util.ArrayList<Param> p = getModules();
		for (final Param pa : p) {
			if (modules == null || modules.contains(pa.name)) {
				final Object obj = Class.forName(pa.classname).newInstance();
				if (obj instanceof Module) {
					final Module mymodule = (Module) obj;
					mymodule.init();
					this.modules.add(mymodule);
				}
			}
		}
	}

	synchronized public void fini() {
		for (int i = modules.size(); i != 0; --i) {
			modules.get(i - 1).fini();
		}
	}
}
